package middleware

import (
	"github.com/gin-gonic/gin"
	"oa_kadia_link/config"
	"oa_kadia_link/globe"
	"oa_kadia_link/utils"
	"strconv"
	"strings"
)

func CheckToken(character string) gin.HandlerFunc {
	return func(context *gin.Context) {
		id := 3
		if !config.GetEnv().DevMode {
			token := context.GetHeader("auth")
			tokenStr := strings.Split(token, "-")
			realIp := utils.GetRealIP(context.Request)
			if len(tokenStr) < 2 {
				globe.FailIpIncr(realIp)
				utils.ErrorJSON(context, "请重新登录！")
				context.Abort()
				return
			}
			accurateToken, _ := globe.GetRdb().Get("[" + character + "Id:token]" + tokenStr[1]).Result()
			if token != accurateToken {
				globe.FailIpIncr(realIp)
				utils.ErrorJSON(context, "请重新登录！")
				context.Abort()
				return
			}
			var err error
			id, err = strconv.Atoi(tokenStr[1])
			if err != nil {
				globe.FailIpIncr(realIp)
				utils.ErrorJSON(context, "请重新登录！")
				context.Abort()
				return
			}
		}
		context.Set(character+"Id", int64(id))
	}
}
